using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.LAKALA;
using Admin.NET.Application.LAKALA.Dto.Request;
using Admin.NET.Application.LAKALA.Dto.Response;
using Admin.NET.Application.Service.LKL.Dto.KeTuo;
using Admin.NET.Core;
using Aliyun.OSS.Util;
using Aspose.Words;
using Furion;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.VirtualFileServer;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using OnceMi.AspNetCore.OSS;
using Yitter.IdGenerator;

namespace Admin.NET.Application.Service.LKL;

[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class LKLPayKTService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<SysFile> _sysFileRep;

	private readonly OSSProviderOptions _OSSProviderOptions;

	private readonly UploadOptions _uploadOptions;

	private readonly IOSSService _OSSService;

	private readonly SqlSugarRepository<AreaBankCode> _area;

	private readonly SqlSugarRepository<UserMerchantKT> _userMer;

	private readonly SqlSugarRepository<LKLDicCode> _rep;

	private readonly SqlSugarRepository<PaymentRecord> _pay;

	private readonly LKLConfigOptions _config;

	private readonly UserManager _userManager;

	private readonly SqlSugarRepository<LKLDicCode> _dic;

	public LKLPayKTService(SqlSugarRepository<SysFile> sysFileRep, IOptions<OSSProviderOptions> oSSProviderOptions, SqlSugarRepository<LKLDicCode> dic, IOptions<UploadOptions> uploadOptions, IOSSServiceFactory ossServiceFactory, SqlSugarRepository<PaymentRecord> pay, UserManager userManager, SqlSugarRepository<LKLDicCode> rep, SqlSugarRepository<AreaBankCode> area, IOptions<LKLConfigOptions> lklconfig, SqlSugarRepository<UserMerchantKT> userMer)
	{
		_dic = dic;
		_sysFileRep = sysFileRep;
		_userManager = userManager;
		_userMer = userMer;
		_rep = rep;
		_area = area;
		_config = lklconfig.Value;
		_pay = pay;
		_OSSProviderOptions = oSSProviderOptions.Value;
		_uploadOptions = uploadOptions.Value;
		if (_OSSProviderOptions.IsEnable)
		{
			_OSSService = ossServiceFactory.Create(Enum.GetName(_OSSProviderOptions.Provider));
		}
	}

	[HttpGet("/ktpay/getsubmer")]
	public async Task<string> GetSubMer(string merChId = "82230104900001H")
	{
		string token = await LKLUtil.GetOrdinaryToken();
		var managerIn = new
		{
			externalCustomerNo = merChId
		};
		string url = "https://tkapi.lakala.com/htkmerchants/open/merchant/info";
		RSAForJava rSAForJava = new RSAForJava();
		string ens = rSAForJava.EncryptByPrivateKey(JsonConvert.SerializeObject(managerIn), _config.PriviceKey);
		var result = new
		{
			data = ens
		};
		CustomerInfoOut modelreulst = await LKLUtil.LKLClientPostKTRequest<CustomerInfoOut>(url, JsonConvert.SerializeObject(result), token);
		if (modelreulst == null || modelreulst.code != "000000")
		{
			throw Oops.Bah("获取商户类别异常");
		}
		string resultRsa = rSAForJava.DecryptByPublicKey(modelreulst.data, _config.PublicKey);
		JsonConvert.DeserializeObject<CustomerMerchantOut>(resultRsa);
		if (result == null)
		{
			throw Oops.Bah("商户新增失败");
		}
		return "";
	}

	private async Task GetWeiChartInfo(UserMerchantKT user)
	{
		string url = "https://s2.lakala.com/api/v2/mms/openApi/wechatRealNameQuery";
		var lKLRequest = new
		{
			reqData = new
			{
				merInnerNo = user.InnerNo,
				version = "1.0",
				orderNo = GetOrderNo(),
				orgCode = "978101"
			},
			ver = "1.0.0",
			timestamp = DateTimeOffset.Now.ToUnixTimeSeconds().ToString(),
			reqId = Guid.NewGuid().ToString().Replace("-", "")
				.ToLower()
		};
		LKLResponseDto<LKLWechartResponse> resultInner = await LKLUtil.LKLClientRequest<LKLResponseDto<LKLWechartResponse>>(url, JsonConvert.SerializeObject(lKLRequest));
		if (resultInner.retCode == "000000")
		{
			user.WeChartCodeErrMsg = resultInner.respData.rejectReason;
			user.WeChartCode = resultInner.respData.applymentState;
			user.WeChartCodeQR = resultInner.respData.qrcodeData;
		}
	}

	private async Task GetAliInfo(UserMerchantKT user)
	{
		string url = "https://s2.lakala.com/api/v2/mms/openApi/alipayRealNameQuery";
		var lKLRequest = new
		{
			reqData = new
			{
				merInnerNo = user.InnerNo,
				version = "1.0",
				orderNo = GetOrderNo(),
				orgCode = "978101",
				subMchId = user.AliSubPayCode
			},
			ver = "1.0.0",
			timestamp = DateTimeOffset.Now.ToUnixTimeSeconds().ToString(),
			reqId = Guid.NewGuid().ToString().Replace("-", "")
				.ToLower()
		};
		LKLResponseDto<LKLAliResponse> resultInner = await LKLUtil.LKLClientRequest<LKLResponseDto<LKLAliResponse>>(url, JsonConvert.SerializeObject(lKLRequest));
		if (resultInner.retCode == "000000")
		{
			user.AliPayCodeErrMsg = resultInner.respData.rejectReason;
			user.AliPayCode = resultInner.respData.applymentState;
			user.AliPayCodeQR = resultInner.respData.qrcodeData;
		}
	}

	/// <summary>
	/// 查询用户
	/// </summary>
	/// <param name="userId"></param>
	/// <returns></returns>
	[HttpGet("/ktpay/customer")]
	public async Task<UserMerchantKT> GetCustomer(long userId)
	{
		UserMerchantKT user = await GetCustomerInfo(userId);
		if (user == null)
		{
			return null;
		}
		string weiChartCode = user.WeChartCodeQR;
		string aliPayCode = user.AliPayCodeQR;
		user.WeChartCodeQR = "";
		user.AliPayCodeQR = "";
		await _userMer.UpdateAsync(user);
		user.WeChartCodeQR = weiChartCode;
		user.AliPayCodeQR = aliPayCode;
		user.bizContent.fees = new List<Fees>();
		return user;
	}

	/// <summary>
	/// ocr识别
	/// </summary>
	/// <param name="customerEditOut"></param>
	/// <returns></returns>
	[HttpPost("/ktpay/ocrpicture")]
	public async Task<object> OcrPicture(OcrResultIn customerEditOut)
	{
		return await LKLUtil.LKLClientPostKTRequest<object>(_config.LKLKTUrl + "/registration/ocr/result", token: await LKLUtil.GetOrdinaryToken(), content: JsonConvert.SerializeObject(customerEditOut));
	}

	/// <summary>
	/// 修改商户基本信息
	/// </summary>
	/// <param name="customerEditOut"></param>
	/// <returns></returns>
	[HttpPost("/ktpay/editcustomerinfo")]
	public async Task EditCustomer(CustomerEditOut customerEditOut)
	{
		UserMerchantKT user = await (from u in _userMer.AsQueryable()
			where u.UserId == (long?)customerEditOut.UserId
			select u).FirstAsync();
		if (user == null)
		{
			throw Oops.Bah("用户信息异常请检查");
		}
		customerEditOut.customerNo = user.MerChId;
		CustomerResponseOut result = await LKLUtil.LKLClientPostKTRequest<CustomerResponseOut>("https://tkapi.lakala.com/htkmerchants/channel/customer/update/basic", token: await LKLUtil.GetEditToken(), content: JsonConvert.SerializeObject(customerEditOut));
		if (result == null)
		{
			throw Oops.Bah("修改商户信息失败");
		}
		if (result.message != "成功")
		{
			throw Oops.Bah(result.message);
		}
		user.merType = customerEditOut.channelType;
		user.licenseNo = customerEditOut.merBlis;
		user.licenseDtEnd = customerEditOut.merBlisExpDt;
		user.licenseName = customerEditOut.merBlisName;
		user.merRegName = customerEditOut.merRegName;
		user.larIdType = customerEditOut.larIdType;
		user.larName = customerEditOut.larName;
		user.larIdCard = customerEditOut.larIdcard;
		user.larIdCardStart = customerEditOut.larIdcardStDt;
		user.larIdCardEnd = customerEditOut.larIdcardExpDt;
		user.merName = customerEditOut.merBizName;
		user.countyCode = customerEditOut.countyCode;
		user.merAddr = customerEditOut.merRegAddr;
		user.contactName = customerEditOut.merContactName;
		user.contactMobile = customerEditOut.merContactMobile;
		user.provinceCode = customerEditOut.provinceCode;
		user.cityCode = customerEditOut.cityCode;
		user.status = "WAIT_AUDI";
		user.attchments.ForEach(delegate(Attchments u)
		{
			Attchments attchments = customerEditOut.fileData.Where((Attchments s) => s.type == u.type).FirstOrDefault();
			if (attchments != null)
			{
				u.id = attchments.id;
				u.SystemUrl = attchments.SystemUrl;
			}
		});
		await _userMer.AsUpdateable(user).UpdateColumns((UserMerchantKT user) => new
		{
			user.merType, user.licenseNo, user.licenseDtEnd, user.licenseName, user.merRegName, user.larIdType, user.larName, user.larIdCard, user.larIdCardStart, user.larIdCardEnd,
			user.merName, user.countyCode, user.merAddr, user.contactName, user.contactMobile, user.provinceCode, user.cityCode, user.status, user.attchments
		}).ExecuteCommandAsync();
	}

	/// <summary>
	/// 修改支付信息
	/// </summary>
	/// <param name="customerEditOut"></param>
	/// <returns></returns>
	[HttpPost("/ktpay/editbank")]
	public async Task EditCustomerBank(CustomerEditBankOut customerEditOut)
	{
		UserMerchantKT user = await (from u in _userMer.AsQueryable()
			where u.UserId == (long?)customerEditOut.UserId
			select u).FirstAsync();
		if (user == null)
		{
			throw Oops.Bah("用户信息异常请检查");
		}
		CustomerResponseOut result = await LKLUtil.LKLClientPostKTRequest<CustomerResponseOut>("https://tkapi.lakala.com/htkmerchants/channel/customer/update/settle/" + user.MerChId, token: await LKLUtil.GetEditToken(), content: JsonConvert.SerializeObject(customerEditOut));
		if (result == null)
		{
			throw Oops.Bah("修改商户结算信息失败");
		}
		if (result.message != "SUCCESS")
		{
			throw Oops.Bah(result.message);
		}
		user.accountType = customerEditOut.accountKind;
		user.accountName = customerEditOut.accountName;
		user.accountNo = customerEditOut.accountNo;
		user.openningBankCode = customerEditOut.bankNo;
		user.openningBankName = customerEditOut.bankName;
		user.clearingBankCode = customerEditOut.clearingBankNo;
		user.settleProvinceCode = customerEditOut.settleProvinceCode;
		user.settleCityCode = customerEditOut.settleCityCode;
		user.settleProvinceName = customerEditOut.settleProvinceName;
		user.settleCityName = customerEditOut.settleCityName;
		user.status = "WAIT_AUDI";
		user.attchments.ForEach(delegate(Attchments u)
		{
			Attchments attchments = customerEditOut.attachments.Where((Attchments s) => s.type == u.type).FirstOrDefault();
			if (attchments != null)
			{
				u.id = attchments.id;
				u.SystemUrl = attchments.SystemUrl;
			}
		});
		await _userMer.AsUpdateable(user).UpdateColumns((UserMerchantKT user) => new
		{
			user.accountType, user.accountName, user.accountNo, user.openningBankCode, user.openningBankName, user.clearingBankCode, user.settleProvinceCode, user.settleCityCode, user.settleProvinceName, user.settleCityName,
			user.status, user.attchments
		}).ExecuteCommandAsync();
	}

	/// <summary>
	/// 修改费率信息
	/// </summary>
	/// <param name="customerEditOut"></param>
	/// <returns></returns>
	[HttpPost("/ktpay/editfee")]
	public async Task EditCustomerFee(CustomerEditFeeIn customerEditOut)
	{
		UserMerchantKT user = await (from u in _userMer.AsQueryable()
			where u.UserId == (long?)customerEditOut.UserId
			select u).FirstAsync();
		if (user == null)
		{
			throw Oops.Bah("用户信息异常请检查");
		}
		string url = "https://tkapi.lakala.com/htkmerchants/channel/customer/update/fee/lsy/" + user.MerChId;
		customerEditOut.customerNo = user.MerChId;
		customerEditOut.productCode = "B2B_SYT";
		CustomerResponseOut result = await LKLUtil.LKLClientPostKTRequest<CustomerResponseOut>(token: await LKLUtil.GetEditToken(), url: url, content: JsonConvert.SerializeObject(customerEditOut));
		if (result == null)
		{
			throw Oops.Bah("修改商户结算信息失败");
		}
		if (result.message != "SUCCESS")
		{
			throw Oops.Bah(result.message);
		}
		user.status = "WAIT_AUDI";
		user.settleType = customerEditOut.settleType;
		user.settlementType = customerEditOut.settlementType;
		user.regularSettlementTime = customerEditOut.regularSettlementTime;
		user.bizContent.withdrawalType = customerEditOut.withdrawalType;
		user.bizContent.fees = customerEditOut.fees;
		await _userMer.AsUpdateable(user).UpdateColumns((UserMerchantKT user) => new
		{
			user.settleType,
			user.settlementType,
			user.regularSettlementTime,
			user.bizContent.withdrawalType,
			user.bizContent.fees,
			user.status
		}).ExecuteCommandAsync();
	}

	private string GetOrderNo()
	{
		Random rand = new Random();
		return DateTime.Now.ToString("yyyyMMddHHmmss").ToString() + rand.Next(10000000, 99999999);
	}

	/// <summary>
	/// 获取商户状态
	/// </summary>
	/// <param name="userid"></param>
	/// <returns></returns>
	[HttpGet("/ktpay/getcustomerinfo")]
	public async Task<UserMerchantKT> GetCustomerInfo(long userid)
	{
		UserMerchantKT user = await (from u in _userMer.AsQueryable()
			where u.UserId == (long?)userid
			select u).FirstAsync();
		if (user == null)
		{
			return user;
		}
		if (user.status != "OPEN")
		{
			string url = "https://tkapi.lakala.com/htkmerchants/open/merchant/info";
			RSAForJava rSAForJava = new RSAForJava();
			string token = await LKLUtil.GetOrdinaryToken();
			var model = new
			{
				customerNo = user.MerChId
			};
			string ens = rSAForJava.EncryptByPrivateKey(JsonConvert.SerializeObject(model), _config.PriviceKey);
			var result = new
			{
				data = ens
			};
			using HttpClient client = HttpClientFactory.Create();
			StringContent stringContent = new StringContent(JsonConvert.SerializeObject(result));
			stringContent.Headers.Remove("Content-Type");
			stringContent.Headers.Add("Content-Type", "application/json");
			client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
			CustomerInfoOut modelreulst = JsonConvert.DeserializeObject<CustomerInfoOut>(await (await client.PostAsync(url, stringContent)).Content.ReadAsStringAsync());
			if (modelreulst == null || modelreulst.code != "000000")
			{
				throw Oops.Bah("获取商户类别异常");
			}
			string resultRsa = rSAForJava.DecryptByPublicKey(modelreulst.data, _config.PublicKey);
			CustomerMerchantOut merchantOut = JsonConvert.DeserializeObject<CustomerMerchantOut>(resultRsa);
			user.status = merchantOut.customer.customerStatus;
			user.ExternalCustomerNo = merchantOut.customer.externalCustomerNo;
		}
		if ((string.IsNullOrEmpty(user.InnerNo) || string.IsNullOrEmpty(user.AliSubPayCode)) && !string.IsNullOrEmpty(user.ExternalCustomerNo))
		{
			string urlNo = "https://s2.lakala.com/api/v2/mms/openApi/querySubMerInfo";
			var lKLRequest = new
			{
				reqData = new
				{
					merCupNo = user.ExternalCustomerNo,
					version = "1.0",
					orderNo = GetOrderNo(),
					orgCode = "978101"
				},
				ver = "1.0.0",
				timestamp = DateTimeOffset.Now.ToUnixTimeSeconds().ToString(),
				reqId = Guid.NewGuid().ToString().Replace("-", "")
					.ToLower()
			};
			LKLResponseDto<LKLGetInnserInfo> resultInner = await LKLUtil.LKLClientRequest<LKLResponseDto<LKLGetInnserInfo>>(urlNo, JsonConvert.SerializeObject(lKLRequest));
			if (!(resultInner.retCode == "000000"))
			{
				throw Oops.Bah("返回信息异常");
			}
			user.InnerNo = resultInner.respData.list[0].merInnerNo;
			user.AliSubPayCode = (from u in resultInner.respData.list
				where u.registerType == "ZFBZF"
				select u.subMchId).FirstOrDefault();
		}
		await GetWeiChartInfo(user);
		await GetAliInfo(user);
		return user;
	}

	/// <summary>
	/// 上传文件
	/// </summary>
	/// <param name="file">文件</param>
	/// <param name="savePath">路径</param>
	/// <returns></returns>
	private async Task<SysFile> HandleUploadFile(IFormFile file, string savePath)
	{
		if (file == null)
		{
			throw Oops.Oh(ErrorCodeEnum.D8000);
		}
		long sizeKb = (long)((double)file.Length / 1024.0);
		string fileMd5 = string.Empty;
		if (_uploadOptions.EnableMd5)
		{
			using (Stream fileStream = file.OpenReadStream())
			{
				fileMd5 = OssUtils.ComputeContentMd5(fileStream, fileStream.Length);
			}
			SysFile sysFile = await _sysFileRep.GetFirstAsync((SysFile u) => u.FileMd5 == fileMd5 && (u.SizeKb == null || u.SizeKb == ((long)sizeKb).ToString()));
			if (sysFile != null)
			{
				return sysFile;
			}
		}
		string path = savePath;
		if (string.IsNullOrWhiteSpace(savePath))
		{
			path = _uploadOptions.Path;
			Regex reg = new Regex("(\\{.+?})");
			MatchCollection match = reg.Matches(path);
			match.ToList().ForEach(delegate(Match a)
			{
				string newValue = DateTime.Now.ToString(a.ToString().Substring(1, a.Length - 2));
				path = path.Replace(a.ToString(), newValue);
			});
		}
		string contentType = "image/png";
		if (!_uploadOptions.ContentType.Contains(contentType))
		{
			throw Oops.Oh(ErrorCodeEnum.D8001);
		}
		if (sizeKb > _uploadOptions.MaxSize)
		{
			throw Oops.Oh(ErrorCodeEnum.D8002);
		}
		string suffix = Path.GetExtension(file.FileName).ToLower();
		if (string.IsNullOrWhiteSpace(suffix))
		{
			FileExtensionContentTypeProvider contentTypeProvider = FS.GetFileExtensionContentTypeProvider();
			suffix = contentTypeProvider.Mappings.FirstOrDefault<KeyValuePair<string, string>>((KeyValuePair<string, string> u) => u.Value == contentType).Key;
			if (suffix == ".jpe")
			{
				suffix = ".jpg";
			}
		}
		if (string.IsNullOrWhiteSpace(suffix))
		{
			throw Oops.Oh(ErrorCodeEnum.D8003);
		}
		SysFile newFile = new SysFile
		{
			Id = YitIdHelper.NextId(),
			BucketName = (_OSSProviderOptions.IsEnable ? _OSSProviderOptions.Bucket : "Local"),
			FileName = Path.GetFileNameWithoutExtension(file.FileName),
			Suffix = suffix,
			SizeKb = sizeKb.ToString(),
			FilePath = path,
			FileMd5 = fileMd5
		};
		string finalName = newFile.Id + suffix;
		if (_OSSProviderOptions.IsEnable)
		{
			newFile.Provider = Enum.GetName(_OSSProviderOptions.Provider);
			string filePath = path + "/" + finalName;
			await _OSSService.PutObjectAsync(newFile.BucketName, filePath, file.OpenReadStream());
			switch (_OSSProviderOptions.Provider)
			{
			case OSSProvider.Aliyun:
				newFile.Url = $"{(_OSSProviderOptions.IsEnableHttps ? "https" : "http")}://{newFile.BucketName}.{_OSSProviderOptions.Endpoint}/{filePath}";
				break;
			case OSSProvider.Minio:
				newFile.Url = $"{(_OSSProviderOptions.IsEnableHttps ? "https" : "http")}://{_OSSProviderOptions.Endpoint}/{newFile.BucketName}/{filePath}";
				break;
			}
		}
		else
		{
			newFile.Provider = "";
			string filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, path);
			if (!Directory.Exists(filePath))
			{
				Directory.CreateDirectory(filePath);
			}
			string realFile = Path.Combine(filePath, finalName);
			using (FileStream stream = File.Create(realFile))
			{
				await file.CopyToAsync(stream);
			}
			newFile.Url = $"{CommonUtil.GetLocalhost()}/{newFile.FilePath}/{newFile.Id + newFile.Suffix}";
		}
		await _sysFileRep.AsInsertable(newFile).ExecuteCommandAsync();
		return newFile;
	}

	/// <summary>
	/// 上传照片
	/// </summary>
	/// <param name="upload"></param>
	/// <param name="type">图片类型</param>
	/// <param name="state">来源0:PC,1:安卓,2:IOS</param>
	/// <returns></returns>
	[HttpPost("/ktpay/uploadimg")]
	public async Task<LKLKTUploadOut> UploadImg([FromForm] Class1 ocr)
	{
		string url = _config.LKLKTUrl + "/registration/file/upload";
		SysFile resultImg = await HandleUploadFile(ocr.upload, "");
		string boundary = DateTime.Now.Ticks.ToString("x");
		using HttpClient httpClient = HttpClientFactory.Create();
		MultipartFormDataContent content = new MultipartFormDataContent(boundary);
		string token = await LKLUtil.GetOrdinaryToken();
		using Stream stream = ocr.upload.OpenReadStream();
		byte[] buffer = new byte[stream.Length];
		stream.Read(buffer, 0, buffer.Length);
		content.Add(new ReadOnlyMemoryContent(Encoding.UTF8.GetBytes(ocr.type)), "\"imgType\"");
		content.Add(new ReadOnlyMemoryContent(Encoding.UTF8.GetBytes(ocr.state)), "\"sourcechnl\"");
		content.Add(new ReadOnlyMemoryContent(Encoding.UTF8.GetBytes("true")), "\"isOcr\"");
		ByteArrayContent fileContent = new ByteArrayContent(buffer);
		fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
		{
			Name = "\"file\"",
			FileName = "\"" + ocr.upload.FileName + "\""
		};
		content.Add(fileContent, "file", ocr.upload.FileName);
		content.Headers.Remove("Content-Type");
		httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
		content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
		LKLKTUploadOut model = JsonConvert.DeserializeObject<LKLKTUploadOut>(await (await httpClient.PostAsync(url, content)).Content.ReadAsStringAsync());
		model.systemUrl = resultImg.Url;
		return model;
	}

	/// <summary>
	/// 拉卡拉商户进件
	/// </summary>
	/// <param name="managerIn"></param>
	/// <returns></returns>
	[HttpPost("/ktpay/addmanager")]
	public async Task KTAddManager(LKLKTManageAddIn managerIn)
	{
		if (await (from u in _userMer.AsQueryable()
			where u.UserId == (long?)managerIn.UserId
			select u).FirstAsync() != null)
		{
			throw Oops.Bah("请不要重复进件");
		}
		string url = _config.LKLKTUrl + "/registration/merchant";
		managerIn.userNo = _config.UserNo;
		managerIn.settlementType = "AUTOMATIC";
		managerIn.bizContent.fees = new List<Fees>
		{
			new Fees
			{
				feeCode = "WECHAT",
				feeValue = 0.6
			},
			new Fees
			{
				feeCode = "ALIPAY",
				feeValue = 0.6
			},
			new Fees
			{
				feeCode = "CREDIT_CARD",
				feeValue = 0.6
			},
			new Fees
			{
				feeCode = "SCAN_PAY",
				feeValue = 0.6
			}
		};
		if (managerIn.accountType == "57")
		{
			UploadPhotoDto uploadPhotoDto = new UploadPhotoDto
			{
				rq = DateTime.Now.ToString("yyyy年MM月dd日"),
				dbr = managerIn.larName,
				khyh = managerIn.openningBankName,
				zhhm = managerIn.accountNo,
				zhmc = managerIn.openningBankName
			};
			LKLKTUploadOut resultInfo = await UploadPhotoOne(uploadPhotoDto);
			managerIn.attchments.Add(new Attchments
			{
				SystemUrl = resultInfo.url,
				id = resultInfo.url,
				type = "OPENING_PERMIT"
			});
		}
		managerIn.attchments.Add(LKLUtil.GetPhoto("CHECKSTAND_IMG"));
		managerIn.attchments.Add(LKLUtil.GetPhoto("SHOP_OUTSIDE_IMG"));
		managerIn.attchments.Add(LKLUtil.GetPhoto("SHOP_INSIDE_IMG"));
		managerIn.attchments.Add(LKLUtil.GetPhoto("BANK_CARD"));
		managerIn.bizContent.termNum = "1";
		managerIn.bizContent.withdrawalType = "SECOND";
		managerIn.bizContent.mcc = "4900";
		managerIn.contactName = managerIn.larName;
		managerIn.accountName = managerIn.larName;
		managerIn.larIdType = "01";
		managerIn.latitude = "117.359967";
		if (string.IsNullOrEmpty(managerIn.merName))
		{
			managerIn.merName = managerIn.larName + "的出租商铺";
			managerIn.merRegName = managerIn.larName + "的出租商铺";
		}
		LKLKTManagerAddOut result = await LKLUtil.LKLClientPostKTRequest<LKLKTManagerAddOut>(token: await LKLUtil.GetOrdinaryToken(), url: url, content: JsonConvert.SerializeObject(managerIn));
		if (result == null)
		{
			throw Oops.Bah("商户新增失败");
		}
		UserMerchantKT user = managerIn.Adapt<UserMerchantKT>();
		user.status = result?.status ?? "-1";
		user.MerChId = result?.merchantNo ?? "-1";
		await _userMer.InsertAsync(user);
	}

	/// <summary>
	/// 拉卡拉商户进件
	/// </summary>
	/// <param name="managerIn"></param>
	/// <returns></returns>
	[HttpPost("/ktpay/editmanager")]
	public async Task KTEditManager(UserMerchantKT managerIn)
	{
		string url = _config.LKLKTUrl + "/registration/merchant";
		managerIn.userNo = _config.UserNo;
		managerIn.settlementType = "AUTOMATIC";
		managerIn.bizContent.fees = new List<Fees>
		{
			new Fees
			{
				feeCode = "WECHAT",
				feeValue = 0.6
			},
			new Fees
			{
				feeCode = "ALIPAY",
				feeValue = 0.6
			},
			new Fees
			{
				feeCode = "CREDIT_CARD",
				feeValue = 0.6
			},
			new Fees
			{
				feeCode = "SCAN_PAY",
				feeValue = 0.6
			}
		};
		managerIn.attchments.Add(LKLUtil.GetPhoto("CHECKSTAND_IMG"));
		managerIn.attchments.Add(LKLUtil.GetPhoto("SHOP_OUTSIDE_IMG"));
		managerIn.attchments.Add(LKLUtil.GetPhoto("SHOP_INSIDE_IMG"));
		managerIn.attchments.Add(LKLUtil.GetPhoto("BANK_CARD"));
		managerIn.bizContent.termNum = "1";
		managerIn.bizContent.withdrawalType = "SECOND";
		managerIn.bizContent.mcc = "4900";
		managerIn.contactName = managerIn.larName;
		managerIn.accountName = managerIn.larName;
		managerIn.larIdType = "01";
		managerIn.latitude = "117.359967";
		if (string.IsNullOrEmpty(managerIn.merName))
		{
			managerIn.merName = managerIn.larName + "的出租商铺";
			managerIn.merRegName = managerIn.larName + "的出租商铺";
		}
		string token = await LKLUtil.GetOrdinaryToken();
		await (from u in _userMer.AsQueryable()
			where u.UserId == managerIn.UserId
			select u).FirstAsync();
		LKLKTManagerAddOut result = await LKLUtil.LKLClientPostKTRequest<LKLKTManagerAddOut>(url, JsonConvert.SerializeObject(managerIn), token);
		if (result == null)
		{
			throw Oops.Bah("商户新增失败");
		}
		managerIn.status = result?.status ?? "-1";
		managerIn.MerChId = result?.merchantNo ?? "-1";
		managerIn.AliPayCode = "";
		managerIn.AliPayCodeErrMsg = "";
		managerIn.WeChartCode = "";
		managerIn.WeChartCodeErrMsg = "";
		managerIn.InnerNo = "";
		await _userMer.UpdateAsync(managerIn);
	}

	/// <summary>
	/// 获取地区编码不穿就是获取最高
	/// </summary>
	/// <param name="areacode"></param>
	/// <returns></returns>
	[HttpGet("/ktpay/getareacode")]
	public async Task<List<LKLKTAreaCodeOut>> GetAreaCode(string areacode = "1")
	{
		List<LKLKTAreaCodeOut> list = new List<LKLKTAreaCodeOut>();
		List<LKLDicCode> listModel = await (from u in _dic.AsQueryable()
			where u.KindCode == 2
			select u).ToListAsync();
		List<LKLDicCode> dicModel = listModel.Where((LKLDicCode u) => u.ParentCode == "1").ToList();
		foreach (LKLDicCode item in dicModel)
		{
			LKLKTAreaCodeOut model = new LKLKTAreaCodeOut
			{
				children = new List<LKLKTAreaCodeOut>(),
				code = item.Code,
				name = item.CodeName,
				parentCode = item.ParentCode
			};
			list.Add(model);
			GetAreaCode(listModel, model, item.Code);
		}
		return list;
	}

	private void GetAreaCode(List<LKLDicCode> dic, LKLKTAreaCodeOut list, string areaCode = "1")
	{
		List<LKLDicCode> info = dic.Where((LKLDicCode u) => u.ParentCode == areaCode).ToList();
		foreach (LKLDicCode item in info)
		{
			LKLKTAreaCodeOut model = new LKLKTAreaCodeOut
			{
				children = new List<LKLKTAreaCodeOut>(),
				code = item.Code,
				name = item.CodeName,
				parentCode = item.ParentCode
			};
			list.children.Add(model);
			GetAreaCode(dic, model, item.Code);
		}
	}

	/// <summary>
	/// 获取银行编码不穿就是获取最高
	/// </summary>
	/// <param name="areacode"></param>
	/// <returns></returns>
	[HttpGet("/ktpay/getbankcode")]
	public async Task<List<LKLKTBankCodeOut>> GetBankCode(string areacode = "1")
	{
		string url = _config.LKLKTUrl + "/registration/organization/bank/" + areacode;
		List<LKLKTBankCodeOut> result = await LKLUtil.LKLClientGetKTRequest<List<LKLKTBankCodeOut>>(url, await LKLUtil.GetOrdinaryToken());
		if (result == null)
		{
			throw Oops.Bah("获取银行编码异常");
		}
		return result;
	}

	/// <summary>
	/// 获取商户类别 不穿就是获取最高
	/// </summary>
	/// <param name="areacode"></param>
	/// <returns></returns>
	[HttpGet("/ktpay/getcustomer")]
	public async Task<List<LKLKTCustomerOut>> GetCustomerType(string areacode)
	{
		string url = _config.LKLKTUrl + "/registration/customer/category/" + areacode;
		List<LKLKTCustomerOut> result = await LKLUtil.LKLClientGetKTRequest<List<LKLKTCustomerOut>>(url, await LKLUtil.GetOrdinaryToken());
		if (result == null)
		{
			throw Oops.Bah("获取商户类别异常");
		}
		return result;
	}

	/// <summary>
	/// 获取银行列表
	/// </summary>
	/// <param name="areacode"></param>
	/// <param name="bankName"></param>
	/// <returns></returns>
	[HttpGet("/ktpay/getbanklist")]
	public async Task<List<LKLKTBankListOut>> GetBankList(string areacode, string bankName)
	{
		if (string.IsNullOrEmpty(areacode))
		{
			throw Oops.Bah("编码不能为空");
		}
		string url = _config.LKLKTUrl + "/registration/bank?areaCode=" + areacode + "&bankName=" + bankName;
		List<LKLKTBankListOut> result = await LKLUtil.LKLClientGetKTRequest<List<LKLKTBankListOut>>(url, await LKLUtil.GetOrdinaryToken());
		if (result == null)
		{
			throw Oops.Bah("获取银行列表异常");
		}
		return result;
	}

	[HttpPost("/ktpay/getbanklistphoto")]
	public async Task<object> UploadPhoto(UploadPhotoDto uploadPhotoDto)
	{
		MemoryStream stream = GetWordsSimple(AppDomain.CurrentDomain.BaseDirectory + "LAKALA/doc/基本账户信息.docx", uploadPhotoDto);
		IFormFile formFile = new FormFile(stream, 0L, stream.Length, "000000", "000000.png");
		Class1 class1 = new Class1
		{
			state = "1",
			type = "OPENING_PERMIT",
			upload = formFile
		};
		return await UploadImg(class1);
	}

	private async Task<LKLKTUploadOut> UploadPhotoOne(UploadPhotoDto uploadPhotoDto)
	{
		MemoryStream stream = GetWordsSimple(AppDomain.CurrentDomain.BaseDirectory + "LAKALA/doc/基本账户信息.docx", uploadPhotoDto);
		IFormFile formFile = new FormFile(stream, 0L, stream.Length, "000000", "000000.png");
		Class1 class1 = new Class1
		{
			state = "1",
			type = "OPENING_PERMIT",
			upload = formFile
		};
		return await UploadImg(class1);
	}

	private MemoryStream GetWordsSimple<T>(string path, T t)
	{
		MemoryStream ms = new MemoryStream();
		Document doc = new Document(path);
		DocumentBuilder builder = new DocumentBuilder(doc);
		Type typet = typeof(T);
		PropertyInfo[] properties = typet.GetProperties();
		foreach (PropertyInfo item in properties)
		{
			string value = item.GetValue(t).ToString();
			builder.MoveToBookmark(item.Name);
			builder.Write(value);
		}
		doc.Save(ms, SaveFormat.Png);
		return ms;
	}
}
